package model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import controller.Admin;

public class DBAdapter {
	
	public static String driver 		= ""; //"oracle.jdbc.driver.OracleDriver";
	public static String dsn 			= ""; //jdbc:oracle:thin:@10.99.168.120:1521:xe
	public static String namespace 		= ""; //BD_DATA
	public static String dbuser 		= ""; //"BD_LIVE"; 	//system
	public static String dbpwd 			= ""; //"geo8f3";	//root
	
	private static Logger theLogger = Logger.getLogger("DBAdapter");
	private Connection con = null;
	
	static {
		try {
			driver 			= Admin.getDriver();
			dsn 			= Admin.getDsn();
			namespace 		= Admin.getNamespace();
			dbuser 			= Admin.getDbuser();
			dbpwd 			= Admin.getDbpwd();
			Class.forName(driver);
		} catch (ClassNotFoundException ee) {
			theLogger.log(Level.SEVERE, "Driver Not Found");
			ee.printStackTrace();
		}
	}
	
	private DBAdapter() {
	}
	
	public static synchronized DBAdapter getInstance() {
		return new DBAdapter();
	}	
	
	public synchronized void open() {
		try {			
//			con = DriverManager.getConnection(dsn + "?" + "user=" + dbuser + "&" + "password=" + dbpwd);
			con = DriverManager.getConnection(dsn, dbuser, dbpwd);
		} catch (Exception e) {
			theLogger.log(Level.SEVERE, "Could not create a connection to DB");
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args) {
		
		String packageQuery = "select * from user";

		String str = "";
		try {
			DBAdapter adapter = DBAdapter.getInstance();
			adapter.open();
			ResultSet rs = adapter.select(packageQuery);
			while (rs.next()) {
				String name = rs.getString("user_name");
				
				
				String detail = "\tname: " + name ;
				theLogger.info(detail);
			}
			adapter.close();
		} catch (SQLException eo) {
			eo.printStackTrace();
		}
	}
	
	
	public synchronized void close() {
		try {
			if(con != null)
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized ResultSet select(String query) {

		ResultSet rs = null;

		try {
			Statement stmt = con.createStatement();
			rs = stmt.executeQuery(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return rs;
	}
	
	public synchronized int update(String query) {

		ResultSet rs = null;
		int status = -1;

		try {
			Statement stmt = con.createStatement();
			status = stmt.executeUpdate(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return status;
	}

}
